package algorithm.leetcode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

/**
 * @author SeonExlike
 * @since 2024/4/16
 */
public class NOA_CombinationSum {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        List<List<Integer>> combinations = new Solution().findCombinations(n, m);
        for (List<Integer> combination : combinations) {
            for (Integer i : combination) {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }

    static class Solution {

        List<List<Integer>> result;

        LinkedList<Integer> current;

        int n;

        public List<List<Integer>> findCombinations(int n, int target) {
            this.result = new ArrayList<>();
            this.current = new LinkedList<>();
            this.n = n;
            backtrack(1, target);
            return result;
        }

        private void backtrack(int start, int remain) {
            if (remain == 0) {
                result.add(new ArrayList<>(current));
                return;
            }

            // remain在不断地递减
            for (int i = start; i <= n; i++) {
                if (i > remain) {
                    // 若本次的i大于余量remain,则直接结束本次递归
                    return;
                }
                current.addLast(i);
                backtrack(i + 1, remain - i);
                current.removeLast();
            }
        }
    }
}
